package cn.jdy.plugins.wap;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.Organ;
import cn.jdy.authority.service.OrganService;
import cn.jdy.common.constant.GlobalConstant;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.common.util.SMSUtil;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.framework.util.HttpUtil;
import cn.jdy.framework.util.JsonUtil;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.plugins.entity.Member;
import cn.jdy.plugins.service.MemberService;
import cn.jdy.plugins.wap.util.EmojiFilter;
 
/**
 * 会员注册控制类
 *
 * @author yangyi
 */
@Controller
@RequestMapping("/register")
public class RegisterCtrl extends BaseCtrl {
	private static String url; // 链接地址
	private static String	appid = "wxcd9ce5b18fd4acd0";
	private static String scope = "snsapi_userinfo"; //静默
	private static String secret="c1ef460fb764389bcd58cadd05b76ba2"; // 公众号的appsecret
	private static	String mchid="1513139041";
	private static String apikey="qau44x04phduq4niid5ebx3uacbm3n2i";
	@Autowired
	private OrganService organService;
	@Autowired
	private MemberService memberService;
	/**
	 * 进入注册页面 授权
	 * 
	 * @param 
	 *          
	 * @return
	 */
	@RequestMapping("/index")
	public String index(String yqm) {
			Organ organ = organService.find("40288119669feb25016717b91a6a0001");

    	 appid=organ.getAppId();
    	 mchid=organ.getMchid();
    	 apikey=organ.getApikey();
    		secret=organ.getAppSecret(); // 公众号的appsecret
    	
	/*	String urls = request.getHeader("Host2") ;
		if (urls.contains(":8080")) {
			url = urls.replaceAll(":8080", "");
		}else{
			url=urls;
		}*/
		if(StringUtil.isNotEmpty(yqm)){
			url="http://kylj.kylj365.com/w/register/toregister?yqm="+yqm;
		}else{
			url="http://kylj.kylj365.com/w/register/toregister";
		}

		BaseLog.e(this.getClass(), "回调地址" + url);
		String cdurl = URLEncoder.encode(url);
		//  明细
		appid = "wxcd9ce5b18fd4acd0";
	//String	secret = weixin.getAppSecret();
//	String	mchid = weixin.getMchid();
//	String	apikey = weixin.getApikey();
		if (null != appid) {
	 
			// 是否强制关注 0 是 -snsapi_base静默授权， 1否-snsapi_userinfo用户手动授权
			// String attention = live.getAttention();
			String attention = "1"; // 静默授权必须关注公众号
			if ("1".equals(attention)) {
				scope = "snsapi_userinfo";
				return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="
						+ appid
						+ "&redirect_uri="
						+ cdurl
						+ "&response_type=code&scope="
						+ scope
						+ "&state=STATE#wechat_redirect";
			} else {
				scope = "snsapi_base";
				return "redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid="
						+ appid
						+ "&redirect_uri="
						+ cdurl
						+ "&response_type=code&scope="
						+ scope
						+ "&state=123#wechat_redirect";
			}

		} else {
			// 跳转到错误界面
			BaseLog.i(this.getClass(), "失败！");
			return "redirect:/register" ;
		}

	}
	/**
	 * 进入注册页面 授权
	 * 
	 * @param 
	 *          
	 * @return
	 */
	@RequestMapping("/totoindex")
	public ModelAndView totoindex(String yqm) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("yqm", yqm);
		mv.setViewName("/member/tuiguang.jsp");

		return mv;

	}
	/**
	 * 获取微信用户信息
	 * 
	 * @return
	 */
	@RequestMapping("/toregister")
	public ModelAndView toregister(String code,String yqm) {
		BaseLog.e(this.getClass(), "code=" + code+"---yqm=" + yqm);
		ModelAndView mv = new ModelAndView();
		// 获取用户基本信息
		Map<String, Object> watchUser = new HashMap<String, Object>();
		try {
			if (!StringUtil.isEmpty(code)) { // code不为空
				 System.out.println("当前返回用户size.........");
				watchUser = toCode(code);
				 System.out.println("当前返回用户size........."+watchUser);
				if (null != watchUser && 0 < watchUser.size()) {
				
					if(StringUtil.isNotEmpty(yqm)){
						Member mb=memberService.findOne("myyqm",yqm);
						if(mb!=null){
							mv.addObject("member", mb);
						}
					}
				
					mv.addObject("watchUser", watchUser);
					 System.out.println("当前返回用户size........."+watchUser);
					mv.setViewName("register.jsp");
					return mv;
				} else {
					// 错误页面
					if(StringUtil.isNotEmpty(yqm)){
						mv.setViewName("redirect:/register/index?yqm="+yqm);
					}else{
						mv.setViewName("redirect:/register/index");
					}

				
					return mv;
				}
			} else {// code为空
				System.err.println("获取网页授权code失败!");
				BaseLog.i(this.getClass(), "获取用户信息失败！");
				// 错误页面
				if(StringUtil.isNotEmpty(yqm)){
					mv.setViewName("redirect:/register/index?yqm="+yqm);
				}else{
					mv.setViewName("redirect:/register/index");
				}

				return mv;
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "网页授权异常！", e);
			// 错误页面
			if(StringUtil.isNotEmpty(yqm)){
				mv.setViewName("redirect:/register/index?yqm="+yqm);
			}else{
				mv.setViewName("redirect:/register/index");
			}

			return mv;
		}

	}
	
	/**
	 * 获取微信用户信息
	 * 
	 * @return
	 */
	@RequestMapping("/tomoniChat")
	public ModelAndView tomoniChat(String code,String yqm) {
		ModelAndView mv = new ModelAndView();
		// 获取用户基本信息
		Map<String, Object> watchUser = new HashMap<String, Object>();
		try {
			if (null != code && !"".equals(code)) { // code不为空
			//	watchUser = toCode(code);
				// BaseLog.i(this.getClass(), "当前返回用户size："+watchUser.size());
				
					if(StringUtil.isNotEmpty(yqm)){
						Member mb=memberService.findOne("myyqm",yqm);
						if(mb!=null){
							mv.addObject("member", mb);
						}
					}
				
					mv.addObject("watchUser", watchUser);
					mv.setViewName("register.jsp");
					return mv;
				
			} else {// code为空
				System.err.println("获取网页授权code失败!");
				BaseLog.i(this.getClass(), "获取用户信息失败！");
				// 错误页面
				mv.setViewName("redirect:/registerr");
				return mv;
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "网页授权异常！", e);
			// 返回错误页面
			mv.setViewName("redirect:/register");
			return mv;
		}

	}
	
	/**
	 * 获取微信接口里面的用户信息
	 * 
	 * @param
	 * @return
	 */
	public Map<String, Object> toCode(String code) {
		@SuppressWarnings("unused")
		Organ organ = organService.find("40288119669feb25016717b91a6a0001");
 		System.out.println(appid+"2..................");
   	 appid=organ.getAppId();
   	 mchid=organ.getMchid();
   	 apikey=organ.getApikey();
   		secret=organ.getAppSecret(); // 公众号的appsecret
   	
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		HashMap<String, Object> user = null;
		String openId = null;
		String access_token = null;
		try {
			// 根据code 得到 openid
			String vre = HttpUtil.sendGet(
					"https://api.weixin.qq.com/sns/oauth2/access_token?appid="
							+ appid + "&secret=" + secret + "&code=" + code
							+ "&grant_type=authorization_code", "UTF-8");
			HashMap<String, Object> map = (HashMap<String, Object>) JsonUtil
					.toObj(vre, Map.class);
			System.out.println(appid+"1234567");
			if (map.containsKey("openid")) {
				openId = map.get("openid").toString();
			}

			if (map.containsKey("access_token")) {
				access_token = map.get("access_token").toString();
			}
			BaseLog.i(this.getClass(), vre + ">>>>>.>>>>>user");
			BaseLog.i(this.getClass(), "当前不存在，获取到token:" + access_token
					+ ",openId:" + openId);

			if (StringUtil.isNotEmpty(openId)
					&& StringUtil.isNotEmpty(access_token)
					&& scope.equals("snsapi_userinfo")) {
				// 根据openid token 得到 用户信息
				String oep = HttpUtil.sendGet(
						"https://api.weixin.qq.com/sns/userinfo?access_token="
								+ access_token + "&openid=" + openId
								+ "&lang=zh_CN", "UTF-8");
				user = (HashMap<String, Object>) JsonUtil.toObj(oep, Map.class);
				BaseLog.i(this.getClass(), oep + ">>>>>.>>>>>user");
				// System.out.println(oep + ">>>>>.>>>>>user ");
			} else if (StringUtil.isNotEmpty(openId)
					&& StringUtil.isNotEmpty(access_token)
					&& scope.equals("snsapi_base")) {
				String oep = HttpUtil.sendGet(
						"https://api.weixin.qq.com/cgi-bin/user/info?access_token="
								+ access_token + "&openid=" + openId
								+ "&lang=zh_CN", "UTF-8");
				// user = (HashMap<String, Object>) JsonUtil.toObj(oep,
				// Map.class);
			}
		} catch (IOException e) {
			e.printStackTrace();
			BaseLog.e(this.getClass(), "获取用户信息失败！", e);
		}

		return user;
	}
  /**
   * 注册初始化
   */
  @RequestMapping("")
  public ModelAndView register(){
	  ModelAndView mv = new ModelAndView("/register.jsp");
    return mv;
  }
  
  /**
   * 用户注册页面
   */
  @RequestMapping("/registerIndex")
  public ModelAndView registerIndex() {
    ModelAndView mv = new ModelAndView("/register.jsp");
    return mv;
  }
  /**
	 * @return /web/register/forSaveMember?username=test&password=123456
	 * @title : 保存注册会员信息
	 * @description: 保存注册信息 跳转到首页或前一个页面
	 * @author: wuzhiliang
	 * @date: 2014-03-13 16:53
	 */
	@RequestMapping("/forSaveMember1")
	public ModelAndView forSaveRegisterMember1(Member memberBo,String authcode) {
		ModelAndView mv = new ModelAndView();
//		if(null == request.getSession().getAttribute(GlobalConstant._PHONECODE)||!authcode.equals(request.getSession().getAttribute(GlobalConstant._PHONECODE))){
//		  mv.setViewName("/register.jsp");
//    mv.addObject("msg", "短信验证码无效！");
//    return mv;
//		}
		  
		try {
			memberBo.setUserType("0");// 个人注册
			memberBo = memberService.saveMember(memberBo);
//			memberService.updateMoney(memberBo.getId(), GlobalConstant.SMONEY_REGISTER);
			session.setAttribute("user", memberBo);// 设置登录状态
			mv.addObject("msg", "注册成功");
//			mv.setViewName("/login.jsp");
			mv.setViewName("/index.jsp");
		} catch(BaseException e) {
			mv.setViewName("/register.jsp");
			mv.addObject("msg", "注册失败！");
			BaseLog.e(this.getClass(), "保存会员注册信息错误", e);
		}
		return mv;
	}
	/**
	 * @title : 保存注册会员信息
	 * @description: 保存注册信息 跳转到首页或前一个页面
	 * @author: wuzhiliang
	 * @date: 2014-03-13 16:53
	 */
	@RequestMapping("/forSaveMember")
    @ResponseBody
    public Map<String, Object> forSaveRegisterMember(Member memberBo,String authcode) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
	if(null == request.getSession().getAttribute(GlobalConstant._PHONECODE)||!authcode.equals(request.getSession().getAttribute(GlobalConstant._PHONECODE))){
			jsonMap.put("msg", "短信验证码无效！");
				return jsonMap;
		}
 
		try {
			memberBo.setUserType("0");// 个人注册
			memberBo.setUserName(memberBo.getMobile());
			//过滤表情
			EmojiFilter  ef=new EmojiFilter();
			memberBo.setNickName(ef.filterEmoji(memberBo.getNickName()));
			
			memberBo = memberService.saveMember(memberBo);
		//	memberService.updateMoney(memberBo.getId(), GlobalConstant.SMONEY_REGISTER);//添加积分
			session.setAttribute("user", memberBo);// 设置登录状态
			jsonMap.put("msg", "200");
			//mv.setViewName("redirect:/");// 跳转到首页
		} catch(BaseException e) {
			jsonMap.put("msg", "注册失败！");
			BaseLog.e(this.getClass(), "保存会员注册信息错误", e);
		}
		return jsonMap;
	}

	/**
	 * @title : udpate保存注册会员信息
	 * @description: 保存注册信息 跳转到首页或前一个页面
	 * @author: wuzhiliang
	 * @date: 2014-03-13 16:53
	 */
	@RequestMapping("/udpateSaveMember")
    @ResponseBody
    public Map<String, Object> udpateSaveMember(Member memberBo,String authcode) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
	if(null == request.getSession().getAttribute(GlobalConstant._PHONECODE)||!authcode.equals(request.getSession().getAttribute(GlobalConstant._PHONECODE))){
			jsonMap.put("msg", "短信验证码无效！");
				return jsonMap;
		}
 
		try {
			Member	membe1r =memberService.findOne("mobile",memberBo.getMobile());
			membe1r.setPassword(SafeUtil.md5(memberBo.getPassword()).substring(8, 16));
			memberService.update(membe1r);
		//	memberService.updateMoney(memberBo.getId(), GlobalConstant.SMONEY_REGISTER);//添加积分
		//	session.setAttribute("user", memberBo);// 设置登录状态
			jsonMap.put("msg", "200");
			//mv.setViewName("redirect:/");// 跳转到首页
		} catch(BaseException e) {
			jsonMap.put("msg", "注册失败！");
			BaseLog.e(this.getClass(), "保存会员注册信息错误", e);
		}
		return jsonMap;
	}

	/**
	 * @title  校验用户名是否被占用
	 * @author  wuzhiliang
	 * @date  2014-03-13 16:53
	 */
	@RequestMapping("/checkUnickusername")
	@ResponseBody
	public Map<String, Object> checkUnickusername(String param) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if(memberService.findcheckUsername(param) > 0) {
			jsonMap.put("status", "n");
			jsonMap.put("info", "该用户已注册，请更换一个");
		} else {
			jsonMap.put("status", "y");
		}
		return jsonMap;
	}

	/**
	 * @return
	 * @title
	 * @description: 校验手机号是否被占用
	 * @author: wuzhiliang
	 * @date: 2014-03-13 16:53
	 */
	@RequestMapping("/checkUnickmobile")
	@ResponseBody
	public Map<String, Object> checkUnickmobile(String param) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if(memberService.findcheckUsermobile(param) > 0) {
			jsonMap.put("status", "n");
			jsonMap.put("info", "该手机号已被注册");
		} else {
			jsonMap.put("status", "y");
		}
		return jsonMap;
	}

	/**
	 * @return
	 * @title
	 * @description: 校验短信验证码
	 * @author: wuzhiliang
	 * @date: 2014-03-13 16:53
	 */
	@RequestMapping("/checkAuthcode")
	@ResponseBody
	public Map<String, Object> checkAuthcode(String param) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if(param!=null && param.equals(request.getSession().getAttribute(GlobalConstant._PHONECODE))) {
			jsonMap.put("status", "y");
		} else {
			jsonMap.put("status", "n");
			jsonMap.put("info", "验证码错误");
		}
		return jsonMap;
	}

	/**
	 * @return
	 * @title
	 * @description: 校验验证码
	 * @author: wuzhiliang
	 * @date: 2014-03-13 16:53
	 */
	@RequestMapping("/checkVerifyCode")
	@ResponseBody
	public Map<String, Object> checkVerifyCode(String authcode) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		if(authcode.equals(request.getSession().getAttribute("verifyCode"))) {
			jsonMap.put("success", "0");
		} else {
			jsonMap.put("success", "1");
		}
		return jsonMap;
	}

	/**
	 * @return
	 * @title
	 * @description: AIAX方式校验短信验证码
	 * @author: wuzhiliang
	 * @date: 2014-03-13 16:53
	 */
	@RequestMapping("/checkAuthcodeString")
	@ResponseBody
	public String checkAuthcodeString(String authcode) {
		if(authcode.equals(request.getSession().getAttribute(GlobalConstant._PHONECODE))) {
			return "true";
		}
		return "false";
	}
	

	/**
	 * @title  校验用户名是否被占用
	 * @author  wuzhiliang
	 * @throws IOException 
	 * @date  2014-03-13 16:53
	 */
	@RequestMapping("/isiponems")
	@ResponseBody
	public Map<String, Object> isiponems(String ipone) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

			String yzm=generateRandom()+"";
			
					if(memberService.findcheckUseropen(ipone) > 0) {
						jsonMap.put("status", "0");
					}else{
						jsonMap.put("status", "1");
						try {
							SMSUtil su=new SMSUtil(); 
							su.smsxw(ipone+"",yzm);
							session.setAttribute(GlobalConstant._PHONECODE, yzm);// 设置登录状态
							
						//	jsonMap.put("yzm", yzm);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							jsonMap.put("yzm", "0");
							e.printStackTrace();
						}
					}
					
			
		return jsonMap;
	}
	

	/**
	 * @title  校验用户名是否被占用
	 * @author  wuzhiliang
	 * @throws IOException 
	 * @date  2014-03-13 16:53
	 */
	@RequestMapping("/isiponemspasswrof")
	@ResponseBody
	public Map<String, Object> isiponemspasswrof(String ipone) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

			String yzm=generateRandom()+"";
			
					if(memberService.findcheckUseropen(ipone) > 0) {
						jsonMap.put("status", "1");
						try {
							SMSUtil su=new SMSUtil(); 
							su.smsxw(ipone+"",yzm);
							session.setAttribute(GlobalConstant._PHONECODE, yzm);// 设置登录状态
							
						//	jsonMap.put("yzm", yzm);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							jsonMap.put("yzm", "0");
							e.printStackTrace();
						}
					}
					
			
		return jsonMap;
	}
	
	/**
	 * @title  发验证码
	 * @author jga
	 * @throws IOException 
	 * @date  2018-10-13 16:53
	 */
	@RequestMapping("/fasongyanzm")
	@ResponseBody
	public Map<String, Object> fasongyanzm(String ipone) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

			String yzm=generateRandom()+"";
			
				
						jsonMap.put("status", "1");
						try {
							SMSUtil su=new SMSUtil(); 
							su.smsxw(ipone+"",yzm);
							session.setAttribute(GlobalConstant._PHONECODE, yzm);// 设置登录状态
							
						//	jsonMap.put("yzm", yzm);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							jsonMap.put("yzm", "0");
							e.printStackTrace();
						}
					
					
			
		return jsonMap;
	}
	
	
	/**
	* 随机生成 6位数字 
	* 
	* @param num
	* @return
	*/
	public static  int generateRandom() {
		return	(int)((Math.random()*9+1)*100000);
	}
	 
	
	/**
	 * @title : 忘记密码
	 * @description:  
	 * @author: jga
	 * @date: 2014-03-13 16:53
	 */
	@RequestMapping("/forSavepassword")
	   @ResponseBody
	    public Map<String, Object> forSavepassword(Member memberBo,String authcode) {
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			if(null == request.getSession().getAttribute(GlobalConstant._PHONECODE)||!authcode.equals(request.getSession().getAttribute(GlobalConstant._PHONECODE))){
				jsonMap.put("msg", "短信验证码无效！");
					return jsonMap;
			}
			try {
				Member  mb=memberService.findOne("mobile",memberBo.getMobile());
				if(mb!=null){
					
					mb.setPassword( SafeUtil.md5(memberBo.getPassword()).substring(8, 16));
					memberService.update(mb);
					
					jsonMap.put("msg", "200");
				}else{
					jsonMap.put("msg", "500");
					jsonMap.put("msg", "没有该用户！");
				}

			} catch(BaseException e) {
				jsonMap.put("msg", "失败！");
			}
			return jsonMap;
		}

		
public static void main(String[] args) {

	try {
		SMSUtil su=new SMSUtil(); 
		su.smsxw("15871027782"+"",generateRandom()+"");
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}



}
